﻿// // ******************************************************************
// //       /\ /|       @file       TranslateRepository.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-03-01 21:03
// //    *(__\_\        @Copyright  Copyright (c) , 2025-02-23 10:02 Await
// // ******************************************************************

using AutomaticSubtitles.Service.DataAccess.Model;
using AutomaticSubtitles.Service.Domain.Translate;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace AutomaticSubtitles.Service.Infrastructure.Repositories;

public class TranslateRepository(AutoDbContext context, IUnitOfWork unitOfWork, IStringLocalizer<SharedResource> localizer) : BaseRepository<AutoDbContext, Auto_Translate, string>
    (context, unitOfWork, localizer), ITranslateRepository
{
    public async Task<Dictionary<string, string>> RetrieveAllCachedData()
    {
        //获取所有的语言类型
        var languages = await context.Auto_Translates.Select(x => new
            {
                x.LanguageType,
                x.TranslatedLanguageType
            })
            .AsNoTracking()
            .Distinct().ToListAsync();
        var dictionary = languages.ToDictionary(x => x.LanguageType, x => x.TranslatedLanguageType);
        var dictionary2 = languages.ToDictionary(x => x.TranslatedLanguageType, x => x.LanguageType);
        dictionary2.ToList().ForEach(x => dictionary.TryAdd(x.Key, x.Value));
        return dictionary;
    }

    public async Task AddDataAsync(List<Auto_Translate> addData)
    {
        await context.AddRangeAsync(addData);
        await context.SaveChangesAsync();
    }

    public async Task UpdateDataAsync(List<Auto_Translate> update)
    {
        try
        {
            // 分批处理实体以避免大事务
            var batchSize = 50;
            for (var i = 0; i < update.Count; i += batchSize)
            {
                var batch = update.Skip(i).Take(batchSize).ToList();

                // 对每个实体单独处理以避免批量更新的冲突
                foreach (var entity in batch)
                    try
                    {
                        // 先从数据库加载当前实体状态
                        var existingEntity = await context.Set<Auto_Translate>()
                            .AsNoTracking()
                            .FirstOrDefaultAsync(e => e.Id == entity.Id);

                        if (existingEntity != null)
                            // 实体存在，使用更新操作
                            context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                        else
                            // 实体不存在，使用添加操作
                            context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                    }
                    catch (Exception ex)
                    {
                        // 记录单个实体处理错误，但继续处理其他实体
                        Console.WriteLine($"处理实体ID={entity.Id}时出错: {ex.Message}");
                    }

                // 每个批次保存一次更改
                await context.SaveChangesAsync();
            }
        }
        catch (Exception ex)
        {
            // 处理其他异常
            Console.WriteLine($"更新数据时发生未预期错误: {ex.Message}");
            throw;
        }
    }

    public async Task<(string? Id, string? Value)> GetValueAsync(string? languageType, string translatedLanguageType, string untranslatedSegmentValue)
    {
        // 如果languageType为空，则返回null
        if (languageType == null) return (null, null);
        // 从Auto_Translates表中查询符合条件的记录
        var firstOrDefaultAsync = await Context.Auto_Translates
            .Where(x => x.LanguageType == languageType && x.TranslatedLanguageType == translatedLanguageType && x.Value == untranslatedSegmentValue)
            .AsNoTracking()
            .FirstOrDefaultAsync();
        // 返回查询结果中的Id和TranslatedValue
        return (firstOrDefaultAsync?.Id, firstOrDefaultAsync?.TranslatedValue);
    }

    public async Task<List<Auto_Subtitle>> GetTranslationRecordAsync(List<Auto_Subtitle> subtitle)
    {
        var autoSubtitles = subtitle.Where(x => x.Language != null).ToList();
        //判断是否被记录过 语言，名称
        var result = await Context.Auto_TranslationRecords.Where(x => autoSubtitles.Select(y => y.Language).Contains(x.TranslatedLanguage) && autoSubtitles.Select(y =>
                y.Name)
            .Contains(x.Name)).ToListAsync();
        //如果记录过，返回未翻译的 也是根据语言，名称
        var unTranslate = autoSubtitles.Where(x => !result.Select(y => y.TranslatedLanguage).Contains(x.Language) && !result.Select(y => y.Name).Contains(x.Name)).ToList();
        return unTranslate;
    }
}